<template>
  <div class="container">
    <!-- Input and buttons -->
    <el-input placeholder="请输入溯源码" v-model.number="traceNumber" clearable class="input-field"></el-input>
    <el-button type="primary" @click="addGoods" class="action-button">添加商品信息</el-button>
    <el-button type="danger" @click="logout" class="action-button logout-button">退出</el-button>

    <!-- Goods list table -->
    <el-table :data="renderList" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }" class="data-table">
      <!-- Trace number column with popover -->
      <el-table-column prop="traceNumber" label="溯源码">
        <template slot-scope="scope">
          <el-popover trigger="click" placement="top" @show="handlePopover(scope.row)" :width="700">
            <GoodDetail :good="popoverData" :block_pro="block_pro" :user="user" />
            <div slot="reference" class="trace-number-link">{{ scope.row.traceNumber }}</div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="date" label="上架时间" sortable></el-table-column>
      <el-table-column prop="quality" label="质检情况"></el-table-column>
      <el-table-column prop="from" label="发货单位"></el-table-column>
      <el-table-column prop="to" label="收货单位"></el-table-column>
    </el-table>

    <!-- Pagination -->
    <el-pagination class="pagination" background :hide-on-single-page="false"
                   @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="currPage"
                   :page-sizes="[10, 20, 50]" :page-size.sync="pageSize" layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>

    <!-- Add goods component -->
    <Retailer :dialogFormVisible="popup" :user="2" :block_pro="block_pro" :block_dis="block_dis" :block_ret="block_ret"
              :good="goodDetail" @popup="handlePopup" @confirmPopup="formSubmit" />
  </div>
</template>

<script>
import axios from 'axios';
import GoodDetail from '../components/GoodDetail.vue';
import Retailer from '../components/Retailer.vue';

export default {
  name: 'Retailers',
  components: {
    Retailer,
    GoodDetail
  },
  data() {
    return {
      popup: false,
      traceNumber: '',
      goodDetail: '',
      goodList: [],
      popoverData: {},
      block_pro: {},
      block_dis: {},
      block_ret: {},
      currPage: 1,
      pageSize: 10,
      total: 0,
      user: 2
    };
  },
  computed: {
    renderList() {
      return this.goodList.slice((this.currPage - 1) * this.pageSize, this.currPage * this.pageSize);
    }
  },
  mounted() {
    this.getData();
  },
  methods: {
    logout() {
      this.$router.push({ name: 'loginview' });
      this.$emit('logout', '');
    },
    getData() {
      axios.get('/retailing')
          .then(ret => {
            this.goodList = ret.data.map(item => ({
              ...item,
              date: this.$dateTime(item.timestamp),
              quality: item.quality === 0 ? '优质' : item.quality === 1 ? '合格' : '不合格'
            })).reverse();
            this.total = this.goodList.length;
          })
          .catch(err => {
            console.error('Error fetching retailing data:', err);
            this.$message.error('获取数据失败');
          });
    },
    async handlePopover(data) {
      if (this.user === 2) {
        this.popoverData = data;
        try {
          const response = await axios.get(`/trace?traceNumber=${data.traceNumber}`);
          this.popoverData.DistributorLocation = response.data[1].location;
        } catch (err) {
          console.error("Failed to fetch distributor location:", err);
          this.$message.error('无法获取分销商位置信息');
        }

        try {
          const producerInfo = await axios.post(`/getBlockInfo`, {
            type: "producer",
            traceNumber: data.traceNumber
          });
          this.block_pro = producerInfo.data.blockInfo;

          const distributorInfo = await axios.post(`/getBlockInfo`, {
            type: "distributor",
            traceNumber: data.traceNumber
          });
          this.block_dis = distributorInfo.data.blockInfo;

          this.popoverData = {
            ...this.popoverData,
            producerInfo: this.block_pro,
            distributorInfo: this.block_dis
          };
        } catch (err) {
          console.error("Failed to fetch block information:", err);
          this.$message.error('无法获取区块信息');
        }
      }
    },
    addGoods() {
      if (!this.traceNumber) {
        this.$message.error('请输入溯源码');
        return;
      }
      axios.get(`/trace?traceNumber=${this.traceNumber}`)
          .then(async ret => {
            this.goodDetail = ret.data || [];
            this.popup = true;

            try {
              const producerInfo = await axios.post(`/getBlockInfo`, {
                type: "producer",
                traceNumber: this.traceNumber
              });
              this.block_pro = producerInfo.data.blockInfo;

              const distributorInfo = await axios.post(`/getBlockInfo`, {
                type: "distributor",
                traceNumber: this.traceNumber
              });
              this.block_dis = distributorInfo.data.blockInfo;

              this.popoverData = {
                ...this.popoverData,
                producerInfo: this.block_pro,
                distributorInfo: this.block_dis
              };
            } catch (err) {
              console.error("Failed to fetch block information:", err);
              this.$message.error('无法获取区块信息');
            }
          })
          .catch(err => {
            console.error('Error adding goods:', err);
            this.$message.error('添加商品信息失败');
          });
    },
    handlePopup(val) {
      this.popup = val;
    },
    formSubmit(val) {
      axios.post(`/addRetail`, {
        ...val,
        quality: parseInt(val.quality),
        traceNumber: this.traceNumber,
        retailerAddress: localStorage.getItem('account')
      })
          .then(ret => {
            if (ret.data.ret !== 1) {
              this.$message.error('提交失败');
              return;
            }
            this.$blockInfo.setBlockInfo("Ret" + this.traceNumber, ret.data.data);
            this.$message.success('提交成功');
            this.getData();
          })
          .catch(err => {
            console.error('Error submitting goods:', err);
            this.$message.error('提交商品信息失败');
          });
      this.popup = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currPage = val;
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.8); /* 稍微透明的白色背景 */
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  margin: 20px auto;
  max-width: 1200px;
}

.input-field {
  width: 300px;
  margin-bottom: 20px;
}

.action-button {
  margin-left: 5px;
  margin-top: 20px;
  margin-right: 10px;
  border-radius: 5px;
}

.logout-button {
  float: right;
  margin-bottom: 20px;
  background-color: #dc3545; /* 红色 */
  border-color: #dc3545;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
}

.logout-button:hover {
  background-color: #EE5C42;
}

.trace-number-link {
  color: #1E90FF;
  cursor: pointer;
}

.trace-number-link:hover {
  text-decoration: underline;
}

.data-table {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
}


.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

.el-table td {
  padding: 12px 10px;
  font-size: 14px;
}

</style>
